<?php
if(!isset($_SESSION)) session_start();

include("./API/BookClass.php");
include("./API/APIObject.php");
include("./API/Code/Filter.php");
/*
    $_SESSION["selectedRoom"]["surchargeTotal"] = $surchargeTotal;
    $_SESSION["selectedRoom"]["hotelId"] = $hotelId;
    $_SESSION["selectedRoom"]["cancellationPolicy"] = $cancellationPolicy;
    $_SESSION["selectedRoom"]["roomcount"] = $roomCount;
$required = array(
    "hotelId" =>$_SESSION["selectedRoom"]["hotelId"],
    "arrivalDate" =>$_SESSION["selectedRoom"]["checkin"],
    "departureDate" =>$_SESSION["selectedRoom"]["checkout"],
    "supplierType" =>$_SESSION["selectedRoom"]["supplierType"],
    "rateKey" =>$_SESSION["selectedRoom"]["rateKey"],
    "roomTypeCode" =>$_SESSION["selectedRoom"]["roomTypeCode"],
    "rateCode" =>$_SESSION["selectedRoom"]["rateCode"],
    "RoomGroup" =>$_SESSION[""],
    "affiliateConfirmationId" =>NULL,
    "affiliateCustomerId" =>NULL,
    "frequentGuestNumber" =>NULL,
    "itineraryId" =>NULL,
    "chargeableRate" =>$_SESSION["selectedRoom"]["total"],
    "specialInformation" =>NULL,
    "sendReservationEmail" =>NULL,
    "reservationInfo" =>??????????,
    "addressInfo" =>????????????,
    "city" =>$_POST[""],
    "stateProvinceCode" =>$_POST[""],
    "countryCode" =>$_POST[""],
    "postalCode" =>$_POST[""];
    
);

$api = new APIObject();
$api->GetReservation($hotelId, $arrivalDate, $departureDate, $supplierType, 
        $rateKey, $roomTypeCode, $rateCode, $RoomGroup, $affiliateConfirmationId, 
        $affiliateCustomerId, $frequentGuestNumber, $itineraryId, $chargeableRate, 
        $specialInformation, $sendReservationEmail, $reservationInfo, $addressInfo, 
        $city, $stateProvinceCode, $countryCode, $postalCode);
*/

$fieldNames = array(
    0 => "contactDetails_email",
    1 => "contactDetails_confirmEmail",
    2 => "contactDetails_phoneNumber",
    3 => "creditCardInformation_cardType",
    4 => "creditCardInformation_cardNumber",
    5 => "cerditCardInformation_cardHolderFirstName",
    6 => "creditCardInformation_cardHolderLastName",
    7 => "creditCardInformation_expirationDate_month",
    8 => "creditCardInformation_expirationDate_year",
    9 => "creditCardInformation_securityCode",
    10 => "billingAdress_country",
    11 => "billingAddress_streetAddres_part1",
    12 => "billingAddress_streetAddres_part2",
    13 => "billingAddress_city",
    14 => "billingAddress_zipCode",
    15 => "billingAddress_state",
    16 => "termsAndConditions",
    17 => "book",
    18 => "supplierType",
    19 => "roomRateKey",
    20 => "roomRateCode",
    21 => "roomTypeCode",
    22 => "hotelId"
);

$sessionVars = array(
    0 => "roomCount",
    1 => "checkIn",
    2 => "checkOut",
);

//Checking if all the data has been sent
$ok = true;
for ($i = 0; $i < 3; $i++) {
    if (!isset($_SESSION["search"][$sessionVars[$i]])){
        $ok = false;
        echo $sessionVars[$i] . " is not ok<br />";
    }
}

if ($ok) {
    for ($i = 1; $i <= $_SESSION["search"]["roomCount"]; $i++) {
        if (!isset($_SESSION["roomsData"][$i]["adults"])){
            $ok = false;
            echo "Room data adults ". $i." is not ok <br />";
        }

        if (!isset($_SESSION["roomsData"][$i]["childrenNr"])){
            $ok = false;
            echo "Room data childrenNr ". $i." is not ok<br />";
        }

        if (!isset($_SESSION["roomsData"][$i]["childrenAge"])){
            $ok = false;
            echo "Room data childrenAge ". $i." is not ok<br />";
        }

        if (!isset($_POST["rooms" . $i . "_smokingPreferenceId"])){
            $ok = false;
            echo "Room data smokingPreferenceId ". $i." is not ok<br />";
        }
         if (!isset($_POST["guest_firstName" . $i])){
            $ok = false;
            echo "Room data guest_firstName ". $i." is not ok<br />";
        }

        if (!isset($_POST["guest_lastName" . $i])){
            $ok = false;
            echo "Room data guest_lastName ". $i." is not ok<br />";
        }
    }
}

for ($i = 1; $i <= 21; $i++) {
    if (!isset($_POST[$fieldNames[$i]])) {
        $ok = false;
    }
}

//Checking if all the data has been sent
if (!$ok) {
    //include("error_booking.php");
    echo "Error.... Not all data has been sent";
} else {
    $api = new APIObject();

// Get Room Availability
    $roomGroup1 = unserialize($_SESSION["roomGroup"]);
    $roomGroup2 = new RoomGroup();
    $roomGroup2->Room = $roomGroup1->Room;
    $guestsCount = 0;
    /*
    $roomAvail = $api->GetRoomAvailability
            (
            $_POST["hotelId"], 
            $_SESSION["search"]["checkIn"], 
            $_SESSION["search"]["checkOut"], NULL, 
            $_POST["supplierType"], 
            $_POST["roomRateKey"], 
            $_POST["roomRateCode"], 
            $_POST["roomTypeCode"], TRUE, TRUE, 
            "HOTEL_DETAILS,ROOM_TYPES,ROOM_AMENITIES,PROPERTY_AMENITIES,HOTEL_IMAGES", 
            $roomGroup2);*/
    
    $book = new Book("55505", "cbrzfta369qwyrm9t5b8y8kf", $_SERVER['REMOTE_ADDR'], "", "15", "en_US", "en_EN", "USD");
    $book_rooms = $_SESSION["step_rooms"];
    

    $book->SetGeneralData
            (
            $book_rooms[0], 
            $book_rooms[1], 
            $book_rooms[2], 
            $book_rooms[3], 
            $book_rooms[4], 
            $book_rooms[5], 
            $book_rooms[6], 
            $book_rooms[7]
    );
    
    for ($i = 1; $i <= $_SESSION["roomsNumber"]; $i++) {
        $guestsCount += $_SESSION["roomsData"][$i]["adults"];
        $roomsData[$i - 1]['numberOfAdults']        = $_SESSION["roomsData"][$i]["adults"];
        $roomsData[$i - 1]['numberOfChildren']      = $_SESSION["roomsData"][$i]["childrenNr"];
        $roomsData[$i - 1]['childAges']             = $_SESSION["roomsData"][$i]["childrenAge"];
        $roomsData[$i - 1]['firstName']             = $_POST["guest_firstName" . $i];
        $roomsData[$i - 1]['lastName']              = $_POST["guest_lastName" . $i];
        $roomsData[$i - 1]['smokingPreference']     = $_POST["rooms" . $i . "_smokingPreferenceId"];
    }
    
    $book->SetGuestsData($_SESSION["roomsNumber"], $roomsData);

    $reservationInfo['email']                       = $_POST["contactDetails_email"];                       //"pufandreipetru@gmail.com";
    $reservationInfo['firstName']                   = $_POST["cerditCardInformation_cardHolderFirstName"];  //"Test Booking";
    $reservationInfo['lastName']                    = $_POST["creditCardInformation_cardHolderLastName"];   //"Test Booking";
    $reservationInfo['homePhone']                   = $_POST["contactDetails_phoneNumber"];                 //"0761256804";
    $reservationInfo['workPhone']                   = $_POST["contactDetails_phoneNumber"];                 //"0761256804";
    $reservationInfo['creditCardType']              = $_POST["creditCardInformation_cardType"];             //"MC";
    $reservationInfo['creditCardNumber']            = $_POST["creditCardInformation_cardNumber"];           //"5401999999999999";
    $reservationInfo['creditCardExpirationMonth']   = $_POST["creditCardInformation_expirationDate_month"]; //"01";
    $reservationInfo['creditCardExpirationYear']    = $_POST["creditCardInformation_expirationDate_year"];  //"2013";
    $reservationInfo['creditCardIdentifier']        = $_POST["creditCardInformation_securityCode"];         //"123";

    $book->SetReservationInfo($reservationInfo);

    $addressInfo['address1']                        = $_POST["billingAddress_streetAddres_part1"];          //"travelnow";
    $addressInfo['city']                            = $_POST["billingAddress_city"];                        //"New York";
    $addressInfo['stateProvinceCode']               = $_POST["billingAddress_state"];                       //"null";
    $addressInfo['countryCode']                     = $_POST["billingAdress_country"];                      //"US";
    $addressInfo['postalCode']                      = $_POST["billingAddress_zipCode"];                     //"12345";

    $book->SetAddressInfo($addressInfo);

    $book->CreateXML_Request();

    //$api->PrintTestDataOnScreen($roomAvail, "");
    
    $bookR = $book->SendRequest();
    $bookRes = json_decode($bookR);
    
    /* If an API error occurs send the users to an error page */
    if(!empty($bookRes->HotelRoomReservationResponse->EanWsError)){
        $_SESSION['book_guard']['postcontents'] = $_POST;
        $_SESSION['searchError'] = $bookRes->HotelRoomReservationResponse->EanWsError->presentationMessage;
        $url ="errorPage.php";
        header("Location:".$url);
        exit();
    }
	
    $_SESSION['book_email'] = $reservationInfo['email'];
    $_SESSION['book_itid'] = $bookRes->HotelRoomReservationResponse->itineraryId;

    if(!empty($_SESSION["logged_user"]) && $_SESSION["logged_bool"] != false){
        include_once 'ItineraryDBclass.php';
        $varIt = new ItineraryDBclass();
        $varIt->connectToDb();
        $userId = $varIt->GetIdUser($_SESSION["logged_user"]);
        $varIt->SetData($userId, $_SESSION['book_itid'], date("Y-m-d"), $_SESSION["book_email"], urldecode($_SESSION["search"]["destination"]), $guestsCount);
        $varIt->insertData();
    }
	
		if($_SESSION["selectedRoom"]){
		unset($_SESSION["selectedRoom"]);
	}
	if($_SESSION["rooms"]){
		unset($_SESSION["rooms"]);
	}
	if($_SESSION["contactDetail"]){
		unset($_SESSION["contactDetail"]);
	}
	
     $url ="confirmationPage.php";
     header("Location:".$url);
}
?>